package com.stars.easyms.demo.rest.service.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.stars.easyms.demo.rest.dto.input.sentinel.SentinelDemo8Input;
import com.stars.easyms.demo.rest.dto.output.sentinel.SentinelDemo8Output;
import com.stars.easyms.rest.RestService;
import com.stars.easyms.base.util.MessageFormatUtil;
import org.springframework.stereotype.Service;

@Service
public class SentinelDemo8Service implements RestService<SentinelDemo8Input, SentinelDemo8Output> {

    @Override
    public SentinelDemo8Output execute(SentinelDemo8Input input) {
        int successCount = 0, blockCount = 0;
        // 单线程循环，无法测试线程类型的限流
        for (int i = 0; i < input.getTimes(); i++) {
            // 循环times次，如果阈值达到则限流抛出BlockException
            try (Entry entry = SphU.entry(input.getResource())) {
                System.out.println(input.getResource());
                successCount++;
            } catch (BlockException e1) {
                blockCount++;
            }
        }
        SentinelDemo8Output output = new SentinelDemo8Output();
        System.out.println(MessageFormatUtil.format("Rest Service[{}], param[{}]!", this.getClass().getSimpleName(), input));
        output.setSuccessCount(successCount);
        output.setBlockCount(blockCount);
        return null;
    }
}